Get premium membership and access questions with answers, video lessons as well as revision papers.

Explain what is wrong with the following program and then fix it. // This program contains an error. #include #include using namespace std; class myclass { int *p; public: myclass(int i); ~myclass()...

      

Explain what is wrong with the following program and then fix it.

// This program contains an error.
#include
#include
using namespace std;
class myclass {
int *p;
public:
myclass(int i);
~myclass() { delete p;}
friend int getval(myclass o);
};
myclass::myclass(int)
{
p = n;
if(!p) {
cout << "Allocation error\n";
exit(1);
}
*p = i;
}
int getval(myclass o)
{
return *o.p; // get value
}
int main()
{
myclass (2);
cout << getval (a) << " " <cout <<"\n";
cout << getval(a) << " " << getval(b);
return 0;
}

  

Answers


Davis
As the program is written, when an object is passed to getval(), a bitwise copy is made. When getval() returns and that copy is destroyed, the memory allocated to that object (which is pointed to by p) is released. However, this is the same memory still required by the object used in the call to getval(). The correct version is;

// This program is now fixed.
#include
#include
using namespace std;
class myclass{
int *p;
public:
myclass(int i);
myclass(const myclass &o); // Copy constructor
~myclass() {delete p;}
friend int getval(myclass o);
};
myclass::myclass(int i)
{
p = new int;
if(!p) {
cout << "Allocatior\n";
exit(1);
}
*p = i;
}
// Copy constructor
myclass::myclass(const myclass &o)
{
p = new int; // allocate copy's own memory
if(!p) {
cout llocation error\n";
exit(1);
}
*p = *o.p;
}
int getval(myclass o)
{
return *o.p; // get value
}
int main ()
{
myclass a(1), b(2);
cout <cout << "\n";
cout << getval(a) << " " << getval(b);
return 0;

Githiari answered the question on May 29, 2018 at 17:49


Next: Imagine a situation in which two classes, called pr1 and pr2, shown below, share one printer.Further imagine that other parts of your program need to...
Previous: Given this particular defined class; class strtype { char *p; int len; public: char *getstring() { return p;} int getlength() { return len;} add two constructor functions. Have the first one...

View More Computer Science Questions and Answers | Return to Questions Index


Learn High School English on YouTube

Related Questions